package com.yakami.ocean.view.activity;

import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.widget.FrameLayout;

import com.yakami.ocean.R;
import com.yakami.ocean.ServerAPI;
import com.yakami.ocean.bean.News;
import com.yakami.ocean.utils.IntentHelper;
import com.yakami.ocean.view.activity.base.BaseHoldBackTabsActivity;
import com.yakami.ocean.view.fragment.AutoNewsListFragment;

import butterknife.Bind;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * @author Yakami, Created on 2016/4/21
 *         popular统一为科普活动代称
 */
public class PopularActivity extends BaseHoldBackTabsActivity {

    @Bind(R.id.view_content) FrameLayout mContent;
    private AutoNewsListFragment mFragment;

    @Override
    protected void onCreate(Bundle savedInstanceBundle) {
        super.onCreate(savedInstanceBundle);

        mTitle.setText(mRes.getText(R.string.ic_popular));

        initTabs(savedInstanceBundle != null);
    }

    @Override
    public void initTabs(boolean isRestarted) {
        super.initTabs(isRestarted);

        mFragment = new AutoNewsListFragment();
        mFragment.setRefreshListener(() -> {
            mFragment.onLoading();
            ServerAPI.getOceanAPI()
                    .getPopularPostList()
                    .subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe((container) -> {
                        mFragment.setData(container.popularList);
                        mFragment.onSuccess();
                    }, throwable -> {
                        throwable.printStackTrace();
                        mFragment.onError();
                    });
        });

        mFragment.setOnItemClickListener((pos, data) -> {
            startActivity(IntentHelper.newInstance(mContext, DetailActivity.class)
                    .putSerializable("data", (News) data)
                    .toIntent());
        });

        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.replace(R.id.view_content, mFragment, "POPULAR");
        transaction.commit();
    }

    @Override
    protected int onBindLayout() {
        return R.layout.activity_popular;
    }

}
